package com.lfy.fyadmin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfy.fyadmin.common.R;
import com.lfy.fyadmin.dto.RoleQueryRequest;
import com.lfy.fyadmin.entity.Role;
import com.lfy.fyadmin.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/role")
@Tag(name = "角色管理", description = "角色相关接口")
public class RoleController {

    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @PostMapping
    @Operation(summary = "新增角色")
    public R<Boolean> save(@RequestBody Role role) {
        boolean result = roleService.save(role);
        return result ? R.ok(true) : R.fail("新增失败");
    }

    @PutMapping
    @Operation(summary = "修改角色")
    public R<Boolean> update(@RequestBody Role role) {
        boolean result = roleService.updateSelective(role);
        return result ? R.ok(true) : R.fail("修改失败");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除角色")
    public R<Boolean> delete(@PathVariable Long id) {
        try {
            boolean result = roleService.deleteRoleWithRelations(id);
            return result ? R.ok(true) : R.fail("删除失败");
        } catch (Exception e) {
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询角色")
    public R<Role> getById(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        return role != null ? R.ok(role) : R.fail("未找到角色");
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询角色")
    public R<IPage<Role>> findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize,
                                   @RequestParam(required = false) String keyword,
                                   @RequestParam(required = false) Integer status,
                                   @RequestParam(required = false) Long roleId) {
        RoleQueryRequest queryRequest = new RoleQueryRequest();
        queryRequest.setPageNum(pageNum);
        queryRequest.setPageSize(pageSize);
        queryRequest.setKeyword(keyword);
        queryRequest.setStatus(status);
        queryRequest.setRoleId(roleId);
        return R.ok(roleService.pageWithConditions(queryRequest));
    }
}